/*
 * @Author: yangzonglong
 * @Date: 2021-05-08 14:07:56
 * @version: v1.0.0
 * @Descripttion: 表单预览
 * @LastEditors: yangzonglong
 * @LastEditTime: 2021-09-14 14:38:59
 * @Auditor:
 */
import React, { useState, useEffect, useRef, forwardRef, useMemo } from 'react';
import { PrintView } from './../../components/fd';
import { getForm, getLformView } from './api';

interface FormViewProps {
  url?: string; // 具体的url
  sessionkey?: string; // session数据获取
  formName?: string; // LFORM所需
  state?: string; // 流程节点线路信息，判断当前所在节点哪些字段可编辑
  formId?: string;
  taskId?: string;
  formDataId?: string;
  isLformHtml?: boolean; // 以html模式加载LFORM
  action?: string; // 指定 postMessage action
  onOk?(data?: string): any;
  onLoad?: () => void;
  disabled?: boolean; // 只对GFORM有效，LFORM 可通过isLformHtml来替代
}
export interface FormViewRefProps {
  getData(): void;
  getGFORM_Data(): void;
}

export default forwardRef(
  ({ url, formId, formDataId, formName, isLformHtml, sessionkey, onLoad, state, taskId, }: FormViewProps, ref: React.Ref<FormViewRefProps>) => {

    const formEngine = useRef('');
    const [formData, setFormData] = useState('');
    const [formInfo, setFormInfo] = useState<any>({});
    const [content, setContent] = useState(''); // 表单结构
    const [enviromentConfig, setEnviromentConfig] = useState(undefined);

    useEffect(() => {
      if (url || (!formId && !formName)) return;

      getForm(formId!, formName!, formDataId).then(async (result) => {
        if (result.length) {
          const [form, formData] = result;
          formData.data = formData.data || (window.top as any)[sessionkey!] || sessionStorage.getItem(sessionkey!);
          let _content: any = null;

          if (form?.formEngine === 'LFORM') {
            // 直接渲染LFORM html模式
            if (isLformHtml) {
              _content = await getLformView(
                form.content,
                typeof formData.data === 'string' && formData.data ? JSON.parse(formData.data) : formData.data
              );
            } else {
              _content = form.content;
            }
          } else {
            // gform
            _content = form.content;
          }

          formEngine.current = form.formEngine;
          setFormData(formData.data);


          setContent(_content);
          setEnviromentConfig(form.enviromentConfig);
          setFormInfo({ formDesc: form.formDesc, formName: form.formName, printScale: form.printScale });
          onLoad?.();
        }
      });
    }, [url, formId, formDataId, isLformHtml, sessionkey, onLoad, formName]);

    const data = useMemo(() => {
      if (!formData) return {};
      return typeof formData === 'string' ? JSON.parse(formData) : formData;
    }, [formData]);

    // 找出在当前节点可编辑的字段
    const [editFields, hideFields] = useMemo(() => {
      if (!state) return [];

      const parseState = JSON.parse(state);
      const huilian = parseState.huilian || {};
      const curTask = huilian[taskId!];

      if (!curTask) return [];

      const lpNodes = curTask.lpNodes || [];
      const invisibleList = curTask.invisibleList || [];

      return [lpNodes.map((item: any) => item.lpKey), invisibleList.map((item: any) => item.controlId)];
    }, [state, taskId]);

    const _structure = useMemo(() => {
      if (content) {
        let _temp = JSON.parse(content);
        _temp.enviromentConfig = enviromentConfig ? JSON.parse(enviromentConfig!) : undefined;
        return _temp;
      }
      return {};
    }, [content, enviromentConfig]);

    return Array.isArray(data) ?
      <div id="arrayPrint" >{
        data.map((item, index) => <div style={{ pageBreakAfter: "always" }} key={index}>
          <PrintView
            hideFields={hideFields}
            formInfo={formInfo}
            data={item}
            structure={_structure}
          />
        </div>)}
      </div>

      : <PrintView
        hideFields={hideFields}
        formInfo={formInfo}
        data={data}
        structure={_structure}
      />;
  }
);
